/*
 * @Date: 2020-09-11 10:46:54
 * @LastEditors: 小枫
 * @LastEditTime: 2020-09-25 20:30:57
 * @FilePath: \feng-blog\app\service\Auth.ts
 */
import { Service } from 'egg';

/**
 * Auth Service
 */
export default class Auth extends Service {

  /**
   * login auth
   * @param username - your username
   * @param password - your password
   */
  public async login(username: string, password: string) {
    const { app } = this;
    const result = await app.mysql.select('users', {
      where: {
        username,
      },
    });
    // // console.log(result, password);
    if (result[0].password === password) {
      return true;
    }
    return false;
  }

  /**
   * 创建用户
   * @param username -用户名
   * @param password -密码
   */
  public async createUser(username: string, password: string) {
    const { app } = this;
    const result = app.mysql.insert('users', {
      username,
      password,
    });
    return result;
  }

  /**
   * 查询与用户
   * @param username -用户名
   */
  public async getUserById(username: string) {
    const { app } = this;
    const user = await app.mysql.select('users', {
      where: {
        username,
      },
    });
    return user;
  }
  /**
   * 生成token
   * @param username -用户名
   */
  public async createToken(username: string) {
    const { app } = this;
    const user = await this.getUserById(username);
    const token = app.jwt.sign({
      uid: user[0].uid,
    }, app.config.jwt.secret);
    return token;
  }

  /**
   * 展示全部用户
   * @param offset -偏移量
   * @param limit -页容量
   */
  public async showAllUsers(offset = 0, limit = 10) {
    const { app } = this;
    const userList = await app.mysql.select('users', {
      columns: [ 'uid', 'username' ],
      offset,
      limit,
    });
    const allCount = userList.length;
    const allPage = Math.ceil(allCount / limit);
    return {
      userList,
      allCount,
      allPage,
    };
  }
}
